package com.foreverwin.mes.lims.controller;

import com.alibaba.fastjson.JSONObject;
import com.foreverwin.mes.common.constants.HandleBOConstants;
import com.foreverwin.mes.core.base.AjaxResult;
import com.foreverwin.mes.core.exception.BusinessException;
import com.foreverwin.mes.core.utils.CommonMethods;
import com.foreverwin.mes.core.utils.StringUtils;
import com.foreverwin.mes.lims.mapper.InspecArrayItemMapper;
import com.foreverwin.mes.lims.model.InspecArrayItem;
import com.foreverwin.mes.lims.model.InspectProjectDetail;
import com.foreverwin.mes.lims.service.InspectProjectDetailService;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import com.foreverwin.mes.lims.service.InspecArrayService;
import com.foreverwin.mes.lims.model.InspecArray;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.sql.Wrapper;
import java.util.*;

/**
 *
 * @author Levy
 * @since 2020-02-17
 */
@Controller
@RequestMapping("/inspecArrays")
public class InspecArrayController {
    private final Logger logger = LoggerFactory.getLogger(InspecArrayController.class);

    @Autowired
    public InspecArrayService inspecArrayService;
    @Autowired
    public InspecArrayItemMapper inspecArrayItemMapper;
    @Autowired
    public InspectProjectDetailService inspectProjectDetailService;

    /**
     * 查询所有检验数组数据
     *
     * @return
     */
    @ResponseBody
    @GetMapping("")
    public AjaxResult getArrayList() {

        List<InspecArray> result = new ArrayList<InspecArray>();
        try {

            String site = CommonMethods.getSite();
            result = inspecArrayService.selectList( site );

        } catch (Exception e) {
            return AjaxResult.error(StringUtils.isBlank(e.getMessage()) ? e.toString() : e.getMessage());
        }
        return AjaxResult.success(result);
    }


    /**
     * 保存检验项目
     *
     * @param jsonObject
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/doSave", method = RequestMethod.POST)
    public AjaxResult stationCertificationSave(@RequestBody JSONObject jsonObject) {

        String site = CommonMethods.getSite();
        String user = CommonMethods.getUser();

        try {

            //参数
            String array = null;
            String description = null;

            Map<String, Object> map = (Map<String, Object>) jsonObject.get("array");
            if (map == null) {
                throw BusinessException.build("参数传递错误");
            }
            if (!map.containsKey("array") || StringUtils.isBlank(map.get("array") + "")) {
                throw BusinessException.build("检验项目编号不能为空");
            }
            if (!map.containsKey("description") || StringUtils.isBlank(map.get("description") + "")) {
                throw BusinessException.build("检验项目描述不能为空");
            }
            array = (String) map.get("array");
            description = (String) map.get("description");

            /**
             * 检验数组主表数据组装
             */
            InspecArray inspecArray = new InspecArray();
            inspecArray.setCheckArray( array );
            inspecArray.setArrayDesc( description );
            inspecArray.setCreatedUser( user );
            inspecArray.setSite( site );

            List<Map> inspectionArrayList = (List<Map>) jsonObject.get("inspectionArrayList");

            if ( inspectionArrayList.isEmpty() ){
                throw BusinessException.build("缺少检验数组明细!");
            }

            inspecArrayService.doSaveData( inspecArray , inspectionArrayList );

        } catch (Exception e) {
            return AjaxResult.error(StringUtils.isBlank(e.getMessage()) ? e.toString() : e.getMessage());
        }

        return AjaxResult.success("检验项目数组维护成功！");
    }

    /**
     * 查询检验项目
     *
     * @param array
     * @return
     */
    @ResponseBody
    @GetMapping("/getArrayItem")
    public AjaxResult getStationAndCertification(String array) {
        Map<String, Object> result = new HashMap<String, Object>();
        String site = CommonMethods.getSite();
        try {
             String handle = HandleBOConstants.INSPEC_ARRAY_BO + ":" + site + "," + array;
            InspecArray inspecArray = inspecArrayService.selectById( handle );
            if (inspecArray == null) {
                throw BusinessException.build("检验项目：" + array + "不存在");
            }

            String arrayBo = inspecArray.getHandle();
            //查询项目明细
            Map paramMap = new HashMap();
            paramMap.put("ARRAY_BO",arrayBo);
            List<InspecArrayItem> inspecArrayItems = inspecArrayItemMapper.selectByMap( paramMap );


            result.put("inspecArray", inspecArray);
            result.put("arrayList", inspecArrayItems);

        } catch (Exception e) {
            return AjaxResult.error(StringUtils.isBlank(e.getMessage()) ? e.toString() : e.getMessage());
        }
        return AjaxResult.success(result);
    }

    /**
     * 删除
     * @param array  传递的Json
     * @return  null 失败
     */
    @ResponseBody
    @GetMapping(  "/doDelete")
    public AjaxResult inspecArrayDelete( String array) {
        String site = CommonMethods.getSite();
        String user = CommonMethods.getUser();
        int count=1;
        try {
            if ( StringUtils.isBlank( array ) ){
                throw  BusinessException.build("检验数组不能为空!");
            }
            String handle =StringUtils.genHandle(  HandleBOConstants.INSPEC_ARRAY_BO , site , array );
            InspecArray inspecArray = inspecArrayService.selectById( handle );
            if ( inspecArray == null ){
                throw  BusinessException.build("检验数组【"+ array +"】信息为空!");
            }
            InspectProjectDetail inspectProjectDetail = new InspectProjectDetail();
            inspectProjectDetail.setArrayName( handle );
            List<InspectProjectDetail> inspectProjectDetails =  inspectProjectDetailService.selectList( inspectProjectDetail );

            if ( !inspectProjectDetails.isEmpty() ){
                throw BusinessException.build("检验数组【"+ array +"】在检验项目中被应用，不可删除!");
            }
            count =  inspecArrayService.deleteById( handle ) ? 1 : 0;
            inspecArrayItemMapper.deleteArrayItemByArrayBo( handle );

        } catch (Exception e) {
            logger.error("inspecArrayDelete -=- {}", e.toString());
            return AjaxResult.error( e.getMessage() );
        }
        return AjaxResult.success(count == 0 ? "删除失败!" : "删除成功!");
    }

}